package com.nettest.action.system;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.nettest.action.BaseJsonAction;
import com.nettest.entity.system.Department;
import com.nettest.entity.system.Role;
import com.nettest.entity.system.Staff;
import com.nettest.service.event.LoginUserCreatedEvent;
import com.nettest.service.event.ResetUserPasswordEvent;
import com.nettest.service.system.DeptService;
import com.nettest.service.system.RoleService;
import com.nettest.service.system.StaffService;
import com.nettest.util.StringUtils;
import com.opensymphony.xwork2.validator.ValidationException;
@Results({
	@Result(name = "success", location = "/WEB-INF/jsp/staff/staffEdit.jsp")})
@Action("staffEdit")
public class StaffEditAction extends BaseJsonAction implements ApplicationContextAware {

    private static final long serialVersionUID = 456254024151703135L;
    private static String PERMISSION_DEPT_EDIT = "STAFF_EDIT";
    private String staffNo;
    private String operate;
    private String newPassword;
    private Staff staff;
    @Autowired
    private StaffService staffService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
	private PasswordEncoder passwordEncoder;
    private ApplicationContext applicationContext;
    @Override
    public String execute() throws Exception {
        if (!StringUtils.isBlank(staffNo)) {
            staff = staffService.getOneStaff(staffNo);
            if (staff != null && !StringUtils.isBlank(staff.getDeptId())) {
                Department dept = deptService.queryDeptById(staff.getDeptId());
                if (dept != null) {
                    staff.setDeptName(dept.getDeptName());
                }
            }
            
            if (staff != null && !staff.getRoles().isEmpty()) {
                StringBuilder roleNames = new StringBuilder();
                StringBuilder roleIds = new StringBuilder();
                for (Role role : staff.getRoles()) {
                	roleNames.append(role.getRoleName()).append(";");
                	roleIds.append(role.getRoleId()).append(";");
				}
                roleNames.deleteCharAt(roleNames.length() - 1);
                roleIds.deleteCharAt(roleIds.length() - 1);
                staff.setRoleName(roleNames.toString());
                staff.setRoleId(roleIds.toString());
            }
        }
        
        return SUCCESS;
    }
    
    @Action(value = "staffSave",results={@Result(name = "success", location = "/WEB-INF/jsp/staff/staffQuery.jsp")})
    public String staffSave() throws Exception {
        if (staff != null) {
            Staff oldStaff = staffService.getOneStaff(staff.getStaffNo());
            if (oldStaff != null) {
                if ("insert".equalsIgnoreCase(operate)) {
                    throw new ValidationException(new StringBuilder("账号'")
                            .append(staff.getStaffNo()).append("'已经被占用！")
                            .toString());
                }
                
                staffService.updateStaff(staff,oldStaff);
            }
            else {
            	staff = staffService.insertStaff(staff);
            	applicationContext.publishEvent(new LoginUserCreatedEvent(this, staff, staff.getPassword()));
            }
        }
        
        return SUCCESS;
    }
    @Action(value = "resetPassword")
    public String resetPassword() throws Exception {
    	if (staff != null) {
    		Staff tempStaff = staffService.getOneStaff(staff.getStaffNo());
    		if (tempStaff != null) {
    			if ("insert".equalsIgnoreCase(operate)) {
    				throw new ValidationException(new StringBuilder("账号'")
    				.append(staff.getStaffNo()).append("'已经被占用！")
    				.toString());
    			}
    			String password = tempStaff.getStaffNo();
    			Object salt = tempStaff.getStaffNo();
        		String encodePassword = passwordEncoder.encodePassword(password , salt );
                tempStaff.setPassword(encodePassword);
    			staffService.save(tempStaff);
    			applicationContext.publishEvent(new ResetUserPasswordEvent(this, tempStaff, password));
    			operate = "reset_success";
    		}    		
    	}
    	
    	return SUCCESS;
    }
    @Action(value = "staffActive",results={@Result(name = "success", location = "/WEB-INF/jsp/staff/staffQuery.jsp")})
    public String updateStatus() throws Exception {
        if (staffNo != null && operate != null) {
            Staff oldStaff = staffService.getOneStaff(staffNo);
            if (oldStaff != null) {
                oldStaff.setActive("Y".equals(operate) ? true : false);
                staffService.save(oldStaff);
            }
        }
        
        return SUCCESS;
    }
    @Action(value = "passwordChange",results={@Result(name = "success", location = "/WEB-INF/jsp/staff/passwordChange.jsp")})
    public String openPassword() throws Exception  {
        return super.execute();
    }
    @Action(value = "saveNewPassword",
    		results={@Result(name = "success", type="redirectAction",params={"actionName","passwordChange","operate","${operate}"})})
    public String changePassword() throws Exception {
        if (staffNo != null && newPassword != null) {
            Staff oldStaff = staffService.getOneStaff(staffNo);
            if (oldStaff != null) {
            	Object salt = oldStaff.getStaffNo();
        		String encodePassword = passwordEncoder.encodePassword(newPassword , salt );
                oldStaff.setPassword(encodePassword);
                staffService.save(oldStaff);
                operate = "passwd_success";
            }
        }
        return SUCCESS;
    }

    public String getStaffNo() {
        return staffNo;
    }

    public void setStaffNo(String staffNo) {
        this.staffNo = staffNo;
    }

    public String getOperate() {
        return operate;
    }

    public void setOperate(String operate) {
        this.operate = operate;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public Staff getStaff() {
        return staff;
    }

    public void setStaff(Staff staff) {
        this.staff = staff;
    }

	public StaffService getStaffService() {
		return staffService;
	}

	public void setStaffService(StaffService staffService) {
		this.staffService = staffService;
	}

	public DeptService getDeptService() {
		return deptService;
	}

	public void setDeptService(DeptService deptService) {
		this.deptService = deptService;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
}
